import { MockMethod } from 'vite-plugin-mock';
import { Random } from 'mockjs';
import { resultError, resultSuccess } from '../_util';
import jwt from 'jsonwebtoken';

function Cookies(cookies: string | string[] | undefined) {
  const array = Array.isArray(cookies) ? cookies : cookies?.split(';') || [];
  return array.reduce((prev, curr) => {
    const cookie = curr.split('=');
    prev[cookie[0]] = cookie[1];
    return prev;
  }, {});
}

export function createFakeUserList() {
  return [
    {
      email: 'admin@polestar.com',
      password: '123456',
      avatar: `https://loremflickr.com/100/100/avatar`,
      token: 'fakeToken@admin',
    },
    {
      email: 'user@polestar.com',
      password: '123456',
      avatar: `https://loremflickr.com/100/100/avatar`,
      token: 'fakeToken@user',
    },
  ];
}

function login(body) {
  const { address, email, password } = body;
  if (address) {
    // const message = new SiweMessage(body.message);
    // const fields = await message.validate(body.signature);
    // if (fields.nonce !== cookies.nonce) {
    //   return resultError('Invalid nonce.');
    // }
    const userInfo = {
      address,
      email: '',
      avatar: `https://loremflickr.com/100/100/avatar`,
      username: Random.name(),
    };
    const token = jwt.sign(userInfo, 'shhhhh', { expiresIn: 60 });
    return resultSuccess({ token });
  } else {
    if (!email) {
      return resultError('缺少邮箱');
    }
    if (!password) {
      return resultError('缺少密码');
    }
    const userInfo = createFakeUserList().find((item) => item.email === email);
    if (!userInfo) {
      return resultError('账号不存在');
    }
    if (userInfo.password !== password) {
      return resultError('密码错误');
    }
    return resultSuccess({ token: userInfo.token });
  }
}

function register(body, cookies) {
  const { email, verifyCode, password, address } = body;
  if (email !== cookies.email) {
    return resultError('未发送验证码');
  }
  if (verifyCode !== cookies.verifyCode) {
    return resultError('验证码无效');
  }
  if (!password) {
    return resultError('缺少密码');
  }
  const userInfo = {
    address: address || '',
    email,
    avatar: `https://loremflickr.com/100/100/avatar`,
    username: Random.name(),
  };
  const token = jwt.sign(userInfo, 'shhhhh', { expiresIn: 60 });
  return resultSuccess(token);
}

export default [
  {
    url: '/basic-api/web/user/open/get_nonce',
    timeout: 500,
    method: 'post',
    response({ body }) {
      console.log(body.address);
      const nonce = Random.natural(8);
      // this.res.setHeader('Set-Cookie', [`nonce=${nonce}; HttpOnly`]);
      return resultSuccess(nonce);
    },
  },
  {
    url: '/basic-api/web/user/open/login',
    timeout: 500,
    method: 'post',
    response({ body }) {
      const result = login(body);
      return result;
    },
  },
  {
    url: '/basic-api/web/user/open/send_validate_code',
    timeout: 500,
    method: 'post',
    response({ body }) {
      console.log(body.email);
      // const verifyCode = Random.natural(6);
      // this.res.setHeader('Set-Cookie', [
      //   `email=${body.email}; HttpOnly`,
      //   `verifyCode=${verifyCode}; HttpOnly`,
      // ]);
      return resultSuccess('ok');
    },
  },
  {
    url: '/basic-api/web/user/open/register',
    timeout: 500,
    method: 'post',
    response({ headers, body }) {
      const cookies = Cookies(headers.cookies);
      const result = register(body, cookies);
      return result;
    },
  },
  {
    url: '/basic-api/web/user/open/logout',
    timeout: 500,
    method: 'get',
    response() {
      return resultSuccess('ok');
    },
  },
  {
    url: '/basic-api/web/user/info',
    timeout: 500,
    method: 'get',
    response({ headers }) {
      const token = headers.authorization;
      const userInfo = createFakeUserList().find((item) => item.token === token);
      if (userInfo) {
        return resultSuccess(userInfo);
      }

      const payload = jwt.verify(token, 'shhhhh');
      if (payload) {
        return resultSuccess(payload);
      }
    },
  },
] as MockMethod[];
